<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>小菊问诊系统</title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/layui@2.8.0/dist/css/layui.css">
    <script src="https://cdn.jsdelivr.net/npm/layui@2.8.0/dist/layui.js"></script>
    <style>
        body, html {
            height: 100%;
            margin: 0;
            padding: 0;
            font-family: 'Microsoft YaHei', Arial, sans-serif;
            background-color: #f0f2f5;
        }
        .chat-container {
            display: flex;
            height: 100vh;
            overflow: hidden;
        }
        /* 左侧会话列表 */
        .chat-sidebar {
            width: 300px;
            background-color: #fff;
            border-right: 1px solid #e6e6e6;
            display: flex;
            flex-direction: column;
            transition: all 0.3s ease;
        }
        .chat-sidebar-header {
            padding: 15px;
            border-bottom: 1px solid #e6e6e6;
            display: flex;
            justify-content: space-between;
            align-items: center;
            background-color: #009688;
            color: white;
        }
        .chat-sidebar-title {
            font-size: 18px;
            font-weight: 600;
        }
        .chat-sidebar-actions {
            display: flex;
            gap: 10px;
        }
        .action-btn {
            width: 32px;
            height: 32px;
            border-radius: 50%;
            background-color: rgba(255, 255, 255, 0.2);
            display: flex;
            justify-content: center;
            align-items: center;
            cursor: pointer;
            transition: all 0.3s ease;
        }
        .action-btn:hover {
            background-color: rgba(255, 255, 255, 0.3);
        }
        .chat-sessions {
            flex: 1;
            overflow-y: auto;
            padding: 10px;
        }
        .session-item {
            padding: 12px;
            margin-bottom: 10px;
            background-color: #f8f8f8;
            border-radius: 8px;
            cursor: pointer;
            transition: all 0.3s ease;
            position: relative;
        }
        .session-item:hover {
            background-color: #f0f0f0;
            transform: translateX(5px);
        }
        .session-item.active {
            background-color: #e0f2f1;
            border-left: 4px solid #009688;
        }
        .session-title {
            font-weight: 600;
            margin-bottom: 5px;
            color: #333;
            font-size: 14px;
        }
        .session-preview {
            color: #666;
            font-size: 12px;
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
            margin-bottom: 5px;
        }
        .session-info {
            display: flex;
            justify-content: space-between;
            font-size: 11px;
            color: #999;
        }
        .session-role {
            color: #009688;
        }
        /* 右侧聊天区域 */
        .chat-main {
            flex: 1;
            display: flex;
            flex-direction: column;
            background-color: #f5f5f5;
        }
        .chat-header {
            padding: 15px 20px;
            background-color: #fff;
            border-bottom: 1px solid #e6e6e6;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }
        .chat-header-info {
            display: flex;
            align-items: center;
            gap: 15px;
        }
        .doctor-avatar {
            width: 40px;
            height: 40px;
            border-radius: 50%;
            background-color: #009688;
            display: flex;
            justify-content: center;
            align-items: center;
            color: white;
            font-size: 20px;
        }
        .chat-header-title {
            display: flex;
            flex-direction: column;
        }
        .chat-title {
            font-size: 16px;
            font-weight: 600;
            color: #333;
        }
        .chat-status {
            font-size: 12px;
            color: #009688;
        }
        .chat-actions {
            display: flex;
            gap: 10px;
        }
        .chat-content {
            flex: 1;
            padding: 20px;
            overflow-y: auto;
            display: flex;
            flex-direction: column;
            gap: 20px;
        }
        .message-item {
            display: flex;
            max-width: 80%;
        }
        .message-item.user {
            align-self: flex-end;
            flex-direction: row-reverse;
        }
        .message-item.ai {
            align-self: flex-start;
        }
        .message-avatar {
            width: 36px;
            height: 36px;
            border-radius: 50%;
            background-color: #e0e0e0;
            display: flex;
            justify-content: center;
            align-items: center;
            margin: 0 10px;
            flex-shrink: 0;
        }
        .message-avatar.user {
            background-color: #009688;
            color: white;
        }
        .message-avatar.ai {
            background-color: #67c23a;
            color: white;
        }
        .message-bubble {
            background-color: #fff;
            border-radius: 12px;
            padding: 12px 16px;
            word-wrap: break-word;
            position: relative;
        }
        .message-item.user .message-bubble {
            background-color: #009688;
            color: white;
        }
        .message-item.ai .message-bubble {
            background-color: #fff;
            color: #333;
            box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
        }
        .message-time {
            font-size: 11px;
            color: #999;
            margin-top: 5px;
            text-align: right;
        }
        .message-item.ai .message-time {
            text-align: left;
        }
        /* 聊天输入区域 */
        .chat-input-container {
            padding: 20px;
            background-color: #fff;
            border-top: 1px solid #e6e6e6;
        }
        .chat-input-wrapper {
            position: relative;
        }
        .chat-input {
            width: 100%;
            min-height: 80px;
            max-height: 160px;
            padding: 12px 50px 12px 12px;
            border: 1px solid #e6e6e6;
            border-radius: 8px;
            resize: none;
            outline: none;
            font-size: 14px;
            transition: border-color 0.3s ease;
        }
        .chat-input:focus {
            border-color: #009688;
        }
        .send-btn {
            position: absolute;
            right: 10px;
            bottom: 10px;
            background-color: #009688;
            color: white;
            border: none;
            padding: 8px 16px;
            border-radius: 4px;
            cursor: pointer;
            transition: all 0.3s ease;
        }
        .send-btn:hover {
            background-color: #00796b;
        }
        .send-btn:disabled {
            background-color: #ccc;
            cursor: not-allowed;
        }
        /* 欢迎提示 */
        .welcome-container {
            display: flex;
            justify-content: center;
            align-items: center;
            height: 100%;
            color: #666;
            text-align: center;
        }
        .welcome-content {
            max-width: 400px;
        }
        .welcome-icon {
            font-size: 80px;
            margin-bottom: 20px;
            color: #009688;
        }
        .welcome-text {
            font-size: 18px;
            margin-bottom: 10px;
        }
        .welcome-subtext {
            font-size: 14px;
            line-height: 1.5;
        }
        /* 模态框样式 */
        .role-selector {
            max-height: 300px;
            overflow-y: auto;
        }
        .role-item {
            padding: 12px;
            border: 1px solid #e6e6e6;
            border-radius: 8px;
            margin-bottom: 10px;
            cursor: pointer;
            transition: all 0.3s ease;
        }
        .role-item:hover {
            border-color: #009688;
            box-shadow: 0 2px 8px rgba(0, 150, 136, 0.1);
        }
        .role-item.selected {
            border-color: #009688;
            background-color: #e0f2f1;
        }
        .role-name {
            font-weight: 600;
            color: #333;
            margin-bottom: 5px;
        }
        .role-description {
            font-size: 12px;
            color: #666;
            line-height: 1.4;
        }
        /* 响应式设计 */
        @media (max-width: 768px) {
            .chat-sidebar {
                width: 260px;
            }
            .message-item {
                max-width: 90%;
            }
        }
        @media (max-width: 600px) {
            .chat-sidebar {
                position: absolute;
                left: -300px;
                z-index: 1000;
                height: 100vh;
                width: 80%;
                max-width: 300px;
            }
            .chat-sidebar.show {
                left: 0;
            }
            .mobile-menu-btn {
                display: block;
            }
        }
        .typing-indicator {
            padding: 12px 16px;
            background-color: #fff;
            border-radius: 12px;
            box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
            display: inline-block;
        }
        .typing-dot {
            width: 8px;
            height: 8px;
            background-color: #999;
            border-radius: 50%;
            display: inline-block;
            margin: 0 2px;
            animation: typing 1.4s infinite ease-in-out both;
        }
        .typing-dot:nth-child(1) {
            animation-delay: -0.32s;
        }
        .typing-dot:nth-child(2) {
            animation-delay: -0.16s;
        }
        @keyframes typing {
            0%, 80%, 100% {
                transform: scale(0);
            }
            40% {
                transform: scale(1);
            }
        }
    </style>
</head>
<body>
    <div class="chat-container">
        <!-- 左侧会话列表 -->
        <div class="chat-sidebar" id="chatSidebar">
            <div class="chat-sidebar-header">
                <div class="chat-sidebar-title">问诊会话</div>
                <div class="chat-sidebar-actions">
                    <div class="action-btn" id="newSessionBtn" title="新建会话">
                        <i class="layui-icon layui-icon-add"></i>
                    </div>
                    <div class="action-btn" id="userInfoBtn" title="个人信息">
                        <i class="layui-icon layui-icon-user"></i>
                    </div>
                </div>
            </div>
            
            <div class="chat-sessions" id="sessionsList">
                <!-- 会话列表将通过JavaScript动态生成 -->
                <div style="text-align: center; padding: 20px; color: #999;">
                    加载中...
                </div>
            </div>
        </div>
        
        <!-- 右侧聊天区域 -->
        <div class="chat-main">
            <div class="chat-header">
                <div class="chat-header-info">
                    <div class="doctor-avatar" id="currentDoctorAvatar">
                        <i class="layui-icon layui-icon-user-circle"></i>
                    </div>
                    <div class="chat-header-title">
                        <div class="chat-title" id="currentChatTitle">请选择或创建会话</div>
                        <div class="chat-status" id="currentChatStatus">
                            <span id="currentDoctorName">AI助手</span> 在线
                        </div>
                    </div>
                </div>
                <div class="chat-actions">
                    <button class="layui-btn layui-btn-sm layui-btn-primary" id="changeDoctorBtn">
                        更换医生
                    </button>
                    <button class="layui-btn layui-btn-sm layui-btn-primary" id="editSessionBtn">
                        编辑会话
                    </button>
                </div>
            </div>
            
            <div class="chat-content" id="chatContent">
                <!-- 欢迎提示 -->
                <div class="welcome-container">
                    <div class="welcome-content">
                        <div class="welcome-icon">
                            <i class="layui-icon layui-icon-chat"></i>
                        </div>
                        <div class="welcome-text">欢迎使用小菊问诊系统</div>
                        <div class="welcome-subtext">
                            请选择一个现有会话或创建新会话<br>
                            与专业AI医生进行健康咨询
                        </div>
                    </div>
                </div>
            </div>
            
            <div class="chat-input-container" id="chatInputContainer" style="display: none;">
                <div class="chat-input-wrapper">
                    <textarea class="chat-input" id="chatInput" placeholder="请输入您的问题..."></textarea>
                    <button class="send-btn" id="sendBtn">发送</button>
                </div>
            </div>
        </div>
    </div>
    
    <!-- 新建会话模态框 -->
    <div id="newSessionModal" style="display: none;">
        <div class="layui-card">
            <div class="layui-card-header">新建问诊会话</div>
            <div class="layui-card-body">
                <form class="layui-form" lay-filter="newSessionForm">
                    <div class="layui-form-item">
                        <label class="layui-form-label">会话标题</label>
                        <div class="layui-input-block">
                            <input type="text" name="title" required lay-verify="required" placeholder="请输入会话标题" class="layui-input">
                        </div>
                    </div>
                    <div class="layui-form-item">
                        <label class="layui-form-label">选择医生</label>
                        <div class="layui-input-block role-selector" id="roleSelector">
                            <!-- 医生列表将通过JavaScript动态生成 -->
                            <div style="text-align: center; padding: 20px; color: #999;">
                                加载中...
                            </div>
                        </div>
                    </div>
                </form>
            </div>
        </div>
    </div>
    
    <!-- 编辑会话模态框 -->
    <div id="editSessionModal" style="display: none;">
        <div class="layui-card">
            <div class="layui-card-header">编辑会话</div>
            <div class="layui-card-body">
                <form class="layui-form" lay-filter="editSessionForm">
                    <input type="hidden" name="session_id">
                    <div class="layui-form-item">
                        <label class="layui-form-label">会话标题</label>
                        <div class="layui-input-block">
                            <input type="text" name="title" required lay-verify="required" placeholder="请输入会话标题" class="layui-input">
                        </div>
                    </div>
                    <div class="layui-form-item">
                        <label class="layui-form-label">状态</label>
                        <div class="layui-input-block">
                            <input type="radio" name="status" value="active" title="进行中" checked>
                            <input type="radio" name="status" value="closed" title="已结束">
                        </div>
                    </div>
                </form>
            </div>
        </div>
    </div>
    
    <script>
        layui.use(['jquery', 'layer', 'form'], function() {
            var $ = layui.jquery;
            var layer = layui.layer;
            var form = layui.form;
            
            var currentSessionId = null;
            var currentRoleId = null;
            var currentRoleName = null;
            
            // 初始化页面
            function initPage() {
                loadSessions();
                loadRoles();
                
                // 绑定事件
                bindEvents();
            }
            
            // 加载会话列表
            function loadSessions() {
                $.ajax({
                    url: '/api/consultations',
                    type: 'GET',
                    success: function(res) {
                        if (res.code === 200) {
                            renderSessions(res.data);
                        } else {
                            $('#sessionsList').html('<div style="text-align: center; padding: 20px; color: #999;">加载失败</div>');
                        }
                    },
                    error: function() {
                        $('#sessionsList').html('<div style="text-align: center; padding: 20px; color: #999;">网络错误</div>');
                    }
                });
            }
            
            // 渲染会话列表
            function renderSessions(sessions) {
                var html = '';
                
                if (sessions.length === 0) {
                    html = '<div style="text-align: center; padding: 20px; color: #999;">暂无会话</div>';
                } else {
                    sessions.forEach(function(session) {
                        var activeClass = session.id === currentSessionId ? 'active' : '';
                        var statusText = session.status === 'active' ? '进行中' : '已结束';
                        var statusClass = session.status === 'active' ? 'active-status' : 'closed-status';
                        
                        html += '<div class="session-item ' + activeClass + '" data-id="' + session.id + '" data-role-id="' + session.role_id + '" data-role-name="' + session.role_name + '">';
                        html += '<div class="session-title">' + session.title + '</div>';
                        html += '<div class="session-preview">' + (session.last_message || '暂无消息') + '</div>';
                        html += '<div class="session-info">';
                        html += '<span class="session-role">' + session.role_name + '</span>';
                        html += '<span>' + formatTime(session.updated_at) + '</span>';
                        html += '</div>';
                        html += '</div>';
                    });
                }
                
                $('#sessionsList').html(html);
                
                // 绑定会话点击事件
                $('.session-item').click(function() {
                    var sessionId = $(this).attr('data-id');
                    var roleId = $(this).attr('data-role-id');
                    var roleName = $(this).attr('data-role-name');
                    
                    selectSession(sessionId, roleId, roleName, $(this).find('.session-title').text());
                });
            }
            
            // 加载AI角色列表
            function loadRoles() {
                $.ajax({
                    url: '/api/ai/roles',
                    type: 'GET',
                    success: function(res) {
                        if (res.code === 200) {
                            renderRoles(res.data);
                        } else {
                            $('#roleSelector').html('<div style="text-align: center; padding: 20px; color: #999;">加载失败</div>');
                        }
                    },
                    error: function() {
                        $('#roleSelector').html('<div style="text-align: center; padding: 20px; color: #999;">网络错误</div>');
                    }
                });
            }
            
            // 渲染角色列表
            function renderRoles(roles) {
                var html = '';
                
                if (roles.length === 0) {
                    html = '<div style="text-align: center; padding: 20px; color: #999;">暂无可用医生</div>';
                } else {
                    roles.forEach(function(role) {
                        html += '<div class="role-item" data-id="' + role.id + '" data-name="' + role.name + '">';
                        html += '<div class="role-name">' + role.name + '</div>';
                        html += '<div class="role-description">' + role.description + '</div>';
                        html += '</div>';
                    });
                }
                
                $('#roleSelector').html(html);
                
                // 绑定角色选择事件
                $('.role-item').click(function() {
                    $('.role-item').removeClass('selected');
                    $(this).addClass('selected');
                    form.val('newSessionForm', {
                        'role_id': $(this).attr('data-id')
                    });
                });
            }
            
            // 选择会话
            function selectSession(sessionId, roleId, roleName, title) {
                currentSessionId = sessionId;
                currentRoleId = roleId;
                currentRoleName = roleName;
                
                // 更新UI
                $('.session-item').removeClass('active');
                $('.session-item[data-id="' + sessionId + '"]').addClass('active');
                
                $('#currentChatTitle').text(title);
                $('#currentDoctorName').text(roleName);
                
                // 显示输入框
                $('#chatInputContainer').show();
                
                // 加载聊天记录
                loadMessages(sessionId);
            }
            
            // 加载聊天记录
            function loadMessages(sessionId) {
                $('#chatContent').html('<div style="text-align: center; padding: 20px; color: #999;">加载中...</div>');
                
                $.ajax({
                    url: '/api/consultations/' + sessionId + '/messages',
                    type: 'GET',
                    success: function(res) {
                        if (res.code === 200) {
                            renderMessages(res.data);
                        } else {
                            $('#chatContent').html('<div style="text-align: center; padding: 20px; color: #999;">加载失败</div>');
                        }
                    },
                    error: function() {
                        $('#chatContent').html('<div style="text-align: center; padding: 20px; color: #999;">网络错误</div>');
                    }
                });
            }
            
            // 渲染聊天记录
            function renderMessages(messages) {
                var html = '';
                
                if (messages.length === 0) {
                    html = '<div style="text-align: center; padding: 40px; color: #999;">开始与医生交流吧</div>';
                } else {
                    messages.forEach(function(message) {
                        var isUser = message.role === 'user';
                        var roleClass = isUser ? 'user' : 'ai';
                        var roleIcon = isUser ? '&#xe664;' : '&#xe663;';
                        
                        html += '<div class="message-item ' + roleClass + '">';
                        html += '<div class="message-avatar ' + roleClass + '">';
                        html += '<i class="layui-icon">' + roleIcon + '</i>';
                        html += '</div>';
                        html += '<div>';
                        html += '<div class="message-bubble">' + message.content + '</div>';
                        html += '<div class="message-time">' + formatTime(message.timestamp) + '</div>';
                        html += '</div>';
                        html += '</div>';
                    });
                }
                
                $('#chatContent').html(html);
                scrollToBottom();
            }
            
            // 发送消息
            function sendMessage(content) {
                if (!currentSessionId || !content.trim()) return;
                
                var messageText = content.trim();
                
                // 显示用户消息
                var userMessageHtml = '';
                userMessageHtml += '<div class="message-item user">';
                userMessageHtml += '<div class="message-avatar user">';
                userMessageHtml += '<i class="layui-icon">&#xe664;</i>';
                userMessageHtml += '</div>';
                userMessageHtml += '<div>';
                userMessageHtml += '<div class="message-bubble">' + messageText + '</div>';
                userMessageHtml += '<div class="message-time">' + formatTime(new Date()) + '</div>';
                userMessageHtml += '</div>';
                userMessageHtml += '</div>';
                
                // 显示AI正在输入
                var typingHtml = '';
                typingHtml += '<div class="message-item ai">';
                typingHtml += '<div class="message-avatar ai">';
                typingHtml += '<i class="layui-icon">&#xe663;</i>';
                typingHtml += '</div>';
                typingHtml += '<div>';
                typingHtml += '<div class="typing-indicator">';
                typingHtml += '<span class="typing-dot"></span>';
                typingHtml += '<span class="typing-dot"></span>';
                typingHtml += '<span class="typing-dot"></span>';
                typingHtml += '</div>';
                typingHtml += '</div>';
                typingHtml += '</div>';
                
                // 清空欢迎界面或现有消息列表
                if ($('.welcome-container').length > 0) {
                    $('#chatContent').html('');
                }
                
                // 添加用户消息和输入指示器
                $('#chatContent').append(userMessageHtml + typingHtml);
                scrollToBottom();
                
                // 清空输入框
                $('#chatInput').val('');
                $('#sendBtn').prop('disabled', true);
                
                // 使用流式请求
                var xhr = new XMLHttpRequest();
                xhr.open('POST', '/api/chat/stream');
                xhr.setRequestHeader('Content-Type', 'application/json');
                xhr.responseType = 'text';
                
                var aiMessageId = 'ai-message-' + Date.now();
                var aiMessageContent = '';
                
                xhr.onloadstart = function() {
                    // 移除输入指示器，准备添加AI消息
                    $('.typing-indicator').closest('.message-item').remove();
                    
                    var aiMessagePlaceholder = '';
                    aiMessagePlaceholder += '<div class="message-item ai" id="' + aiMessageId + '">';
                    aiMessagePlaceholder += '<div class="message-avatar ai">';
                    aiMessagePlaceholder += '<i class="layui-icon">&#xe663;</i>';
                    aiMessagePlaceholder += '</div>';
                    aiMessagePlaceholder += '<div>';
                    aiMessagePlaceholder += '<div class="message-bubble"></div>';
                    aiMessagePlaceholder += '<div class="message-time">' + formatTime(new Date()) + '</div>';
                    aiMessagePlaceholder += '</div>';
                    aiMessagePlaceholder += '</div>';
                    
                    $('#chatContent').append(aiMessagePlaceholder);
                };
                
                xhr.onprogress = function(event) {
                    if (event.lengthComputable) {
                        var response = xhr.responseText;
                        var chunks = response.split('\n');
                        
                        chunks.forEach(function(chunk) {
                            if (chunk.startsWith('data: ')) {
                                try {
                                    var data = JSON.parse(chunk.substring(6));
                                    if (data.content) {
                                        aiMessageContent += data.content;
                                        $('#' + aiMessageId + ' .message-bubble').text(aiMessageContent);
                                        scrollToBottom();
                                    }
                                } catch (e) {
                                    console.error('解析错误:', e);
                                }
                            }
                        });
                    }
                };
                
                xhr.onload = function() {
                    // 请求完成后更新会话列表
                    loadSessions();
                    $('#sendBtn').prop('disabled', false);
                };
                
                xhr.onerror = function() {
                    $('#' + aiMessageId + ' .message-bubble').text('抱歉，请求失败，请稍后重试');
                    $('#sendBtn').prop('disabled', false);
                };
                
                xhr.send(JSON.stringify({
                    session_id: currentSessionId,
                    role_id: currentRoleId,
                    content: messageText
                }));
            }
            
            // 新建会话
            function createSession(title, roleId) {
                $.ajax({
                    url: '/api/consultations',
                    type: 'POST',
                    data: JSON.stringify({ title: title, role_id: roleId }),
                    contentType: 'application/json',
                    success: function(res) {
                        if (res.code === 200) {
                            layer.closeAll();
                            loadSessions();
                            // 自动选择新创建的会话
                            $.ajax({
                                url: '/api/ai/roles/' + roleId,
                                type: 'GET',
                                success: function(roleRes) {
                                    if (roleRes.code === 200) {
                                        selectSession(res.data.id, roleId, roleRes.data.name, title);
                                    }
                                }
                            });
                        } else {
                            layer.msg(res.message || '创建失败');
                        }
                    },
                    error: function() {
                        layer.msg('网络错误');
                    }
                });
            }
            
            // 编辑会话
            function updateSession(sessionId, title, status) {
                $.ajax({
                    url: '/api/consultations/' + sessionId,
                    type: 'PUT',
                    data: JSON.stringify({ title: title, status: status }),
                    contentType: 'application/json',
                    success: function(res) {
                        if (res.code === 200) {
                            layer.closeAll();
                            loadSessions();
                            // 更新当前标题
                            $('#currentChatTitle').text(title);
                        } else {
                            layer.msg(res.message || '更新失败');
                        }
                    },
                    error: function() {
                        layer.msg('网络错误');
                    }
                });
            }
            
            // 删除会话
            function deleteSession(sessionId) {
                $.ajax({
                    url: '/api/consultations/' + sessionId,
                    type: 'DELETE',
                    success: function(res) {
                        if (res.code === 200) {
                            layer.closeAll();
                            // 如果删除的是当前会话，重置界面
                            if (sessionId === currentSessionId) {
                                currentSessionId = null;
                                currentRoleId = null;
                                currentRoleName = null;
                                
                                $('#currentChatTitle').text('请选择或创建会话');
                                $('#currentDoctorName').text('AI助手');
                                $('#chatInputContainer').hide();
                                
                                $('#chatContent').html('<div class="welcome-container">' +
                                    '<div class="welcome-content">' +
                                    '<div class="welcome-icon">' +
                                    '<i class="layui-icon layui-icon-chat"></i>' +
                                    '</div>' +
                                    '<div class="welcome-text">欢迎使用小菊问诊系统</div>' +
                                    '<div class="welcome-subtext">' +
                                    '请选择一个现有会话或创建新会话<br>' +
                                    '与专业AI医生进行健康咨询' +
                                    '</div>' +
                                    '</div>' +
                                    '</div>');
                            }
                            loadSessions();
                        } else {
                            layer.msg(res.message || '删除失败');
                        }
                    },
                    error: function() {
                        layer.msg('网络错误');
                    }
                });
            }
            
            // 格式化时间
            function formatTime(time) {
                var date = new Date(time);
                var now = new Date();
                var diff = now - date;
                
                // 小于1分钟
                if (diff < 60000) {
                    return '刚刚';
                }
                // 小于1小时
                if (diff < 3600000) {
                    return Math.floor(diff / 60000) + '分钟前';
                }
                // 小于24小时
                if (diff < 86400000) {
                    return Math.floor(diff / 3600000) + '小时前';
                }
                // 小于7天
                if (diff < 604800000) {
                    return Math.floor(diff / 86400000) + '天前';
                }
                
                // 其他情况显示具体日期
                var year = date.getFullYear();
                var month = (date.getMonth() + 1).toString().padStart(2, '0');
                var day = date.getDate().toString().padStart(2, '0');
                var hour = date.getHours().toString().padStart(2, '0');
                var minute = date.getMinutes().toString().padStart(2, '0');
                
                // 如果是今年，不显示年份
                if (year === now.getFullYear()) {
                    return month + '-' + day + ' ' + hour + ':' + minute;
                }
                
                return year + '-' + month + '-' + day + ' ' + hour + ':' + minute;
            }
            
            // 滚动到底部
            function scrollToBottom() {
                var chatContent = $('#chatContent')[0];
                chatContent.scrollTop = chatContent.scrollHeight;
            }
            
            // 绑定事件
            function bindEvents() {
                // 新建会话按钮
                $('#newSessionBtn').click(function() {
                    form.val('newSessionForm', {
                        title: '',
                        role_id: ''
                    });
                    $('.role-item').removeClass('selected');
                    
                    layer.open({
                        type: 1,
                        title: '新建问诊会话',
                        content: $('#newSessionModal'),
                        area: ['500px', '450px'],
                        btn: ['创建', '取消'],
                        yes: function(index) {
                            var formData = form.val('newSessionForm');
                            var selectedRole = $('.role-item.selected');
                            
                            if (!formData.title.trim()) {
                                layer.msg('请输入会话标题');
                                return;
                            }
                            
                            if (selectedRole.length === 0) {
                                layer.msg('请选择医生');
                                return;
                            }
                            
                            createSession(formData.title.trim(), selectedRole.attr('data-id'));
                        }
                    });
                });
                
                // 编辑会话按钮
                $('#editSessionBtn').click(function() {
                    if (!currentSessionId) {
                        layer.msg('请先选择会话');
                        return;
                    }
                    
                    var currentSession = $('.session-item.active');
                    form.val('editSessionForm', {
                        session_id: currentSessionId,
                        title: $('#currentChatTitle').text(),
                        status: currentSession.attr('data-status') || 'active'
                    });
                    
                    layer.open({
                        type: 1,
                        title: '编辑会话',
                        content: $('#editSessionModal'),
                        area: ['400px', '300px'],
                        btn: ['保存', '取消', '删除'],
                        btn3: function(index) {
                            layer.confirm('确定要删除此会话吗？', function(confirmIndex) {
                                deleteSession(currentSessionId);
                                layer.close(confirmIndex);
                            });
                        },
                        yes: function(index) {
                            var formData = form.val('editSessionForm');
                            
                            if (!formData.title.trim()) {
                                layer.msg('请输入会话标题');
                                return;
                            }
                            
                            updateSession(formData.session_id, formData.title.trim(), formData.status);
                        }
                    });
                });
                
                // 更换医生按钮
                $('#changeDoctorBtn').click(function() {
                    if (!currentSessionId) {
                        layer.msg('请先选择会话');
                        return;
                    }
                    
                    layer.open({
                        type: 1,
                        title: '更换医生',
                        content: '<div style="padding: 20px;"><div class="role-selector" id="changeRoleSelector"></div></div>',
                        area: ['500px', '400px'],
                        btn: ['确认', '取消'],
                        success: function() {
                            // 重新加载角色列表
                            $.ajax({
                                url: '/api/ai/roles',
                                type: 'GET',
                                success: function(res) {
                                    if (res.code === 200) {
                                        var html = '';
                                        res.data.forEach(function(role) {
                                            var selectedClass = role.id === currentRoleId ? 'selected' : '';
                                            html += '<div class="role-item ' + selectedClass + '" data-id="' + role.id + '" data-name="' + role.name + '">';
                                            html += '<div class="role-name">' + role.name + '</div>';
                                            html += '<div class="role-description">' + role.description + '</div>';
                                            html += '</div>';
                                        });
                                        $('#changeRoleSelector').html(html);
                                        
                                        // 绑定选择事件
                                        $('.role-item').click(function() {
                                            $('.role-item').removeClass('selected');
                                            $(this).addClass('selected');
                                        });
                                    }
                                }
                            });
                        },
                        yes: function(index) {
                            var selectedRole = $('#changeRoleSelector .role-item.selected');
                            if (selectedRole.length > 0) {
                                var roleId = selectedRole.attr('data-id');
                                var roleName = selectedRole.attr('data-name');
                                
                                // 更新会话的医生
                                $.ajax({
                                    url: '/api/consultations/' + currentSessionId + '/change-role',
                                    type: 'PUT',
                                    data: JSON.stringify({ role_id: roleId }),
                                    contentType: 'application/json',
                                    success: function(res) {
                                        if (res.code === 200) {
                                            currentRoleId = roleId;
                                            currentRoleName = roleName;
                                            $('#currentDoctorName').text(roleName);
                                            layer.close(index);
                                            layer.msg('更换成功');
                                            loadSessions();
                                        } else {
                                            layer.msg(res.message || '更换失败');
                                        }
                                    },
                                    error: function() {
                                        layer.msg('网络错误');
                                    }
                                });
                            } else {
                                layer.msg('请选择医生');
                            }
                        }
                    });
                });
                
                // 发送按钮
                $('#sendBtn').click(function() {
                    var content = $('#chatInput').val();
                    if (content.trim()) {
                        sendMessage(content);
                    }
                });
                
                // 输入框事件
                $('#chatInput').on('input', function() {
                    $('#sendBtn').prop('disabled', !$(this).val().trim());
                });
                
                // 回车发送
                $('#chatInput').keydown(function(event) {
                    if (event.keyCode === 13 && !event.shiftKey) {
                        event.preventDefault();
                        $('#sendBtn').click();
                    }
                });
                
                // 个人信息按钮
                $('#userInfoBtn').click(function() {
                    $.ajax({
                        url: '/api/user/info',
                        type: 'GET',
                        success: function(res) {
                            if (res.code === 200) {
                                var user = res.data;
                                layer.open({
                                    type: 1,
                                    title: '个人信息',
                                    content: '<div style="padding: 20px;">' +
                                        '<p><strong>用户名：</strong>' + user.username + '</p>' +
                                        '<p><strong>邮箱：</strong>' + user.email + '</p>' +
                                        '<p><strong>性别：</strong>' + (user.gender === 'male' ? '男' : user.gender === 'female' ? '女' : '其他') + '</p>' +
                                        '<p><strong>注册时间：</strong>' + formatTime(user.created_at) + '</p>' +
                                        '<button class="layui-btn layui-btn-danger layui-btn-sm" style="margin-top: 20px;" id="logoutBtn">退出登录</button>' +
                                        '</div>',
                                    area: ['300px', '250px'],
                                    btn: ['确定'],
                                    success: function() {
                                        $('#logoutBtn').click(function() {
                                            $.ajax({
                                                url: '/auth/logout',
                                                type: 'POST',
                                                success: function(res) {
                                                    if (res.code === 200) {
                                                        window.location.href = '/auth/login';
                                                    }
                                                }
                                            });
                                        });
                                    }
                                });
                            }
                        }
                    });
                });
            }
            
            // 初始化
            initPage();
        });
    </script>
</body>
</html>